//
//  AddressbookViewController.m
//  ACE
//
//  Created by Mickey Yin on 2021/12/9.
//

#import "AddressbookViewController.h"
#import "MineTableViewCell.h"
#import <Contacts/Contacts.h>

@interface AddressbookViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *addressbookList;
@property (nonatomic, strong) AddressbookModel *addressbookModel;


@end

@implementation AddressbookViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    self.navigationItem.title = @"通讯录";
    [self setupUI];
    [self requestContactAuthorAfterSystemVersion9];
}

- (void)setupUI {
    
    [self.view addSubview:self.tableView];
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, KScreenW, KScreenH) style:UITableViewStylePlain];
        _tableView.separatorStyle = UITableViewCellSelectionStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.rowHeight = 50;
    }
    return _tableView;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.addressbookList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MineTableViewCell *cell = [MineTableViewCell cellWithTableView:tableView];
    cell.addressbookModel = self.addressbookList[indexPath.row];
    return cell;
}


//请求通讯录权限
#pragma mark 请求通讯录权限
- (void)requestContactAuthorAfterSystemVersion9 {
    
    // 获得通讯录的授权状态
    CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
    if (status == CNAuthorizationStatusNotDetermined) { //用户未授权
        CNContactStore *store = [[CNContactStore alloc] init];
        [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError*  _Nullable error) {
            if (error) {
                NSLog(@"通讯录授权失败");
            }else {
                NSLog(@"通讯录成功授权");
            }
        }];
    }
    else if(status == CNAuthorizationStatusRestricted) //iOS 设备上一些许可配置阻止程序与通讯录数据库进行交互
    {
        NSLog(@"通讯录授权用户拒绝");
        [self showAlertViewAboutNotAuthorAccessContact];
    }
    else if (status == CNAuthorizationStatusDenied) //用户明确的拒绝了你的程序对通讯录的访问
    {
        NSLog(@"通讯录授权用户拒绝");
        [self showAlertViewAboutNotAuthorAccessContact];
    }
    else if (status == CNAuthorizationStatusAuthorized)//已经授权
    {
        //有通讯录权限-- 进行下一步操作
        [self openContact];
    }
    
}

//有通讯录权限-- 进行下一步操作
- (void)openContact{
    // 获取指定的字段,并不是要获取所有字段，需要指定具体的字段
    NSArray *keysToFetch = @[CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey];
    CNContactFetchRequest *fetchRequest = [[CNContactFetchRequest alloc] initWithKeysToFetch:keysToFetch];
    CNContactStore *contactStore = [[CNContactStore alloc] init];
    
    [contactStore enumerateContactsWithFetchRequest:fetchRequest error:nil usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {
        //拼接姓名
        NSString *nameStr = [NSString stringWithFormat:@"%@%@",contact.familyName,contact.givenName];
        NSArray *phoneNumbers = contact.phoneNumbers;
        
        for (CNLabeledValue *labelValue in phoneNumbers) {
            //遍历一个人名下的多个电话号码
            CNPhoneNumber *phoneNumber = labelValue.value;
            NSString * nustring = phoneNumber.stringValue ;
            
            self.addressbookModel = [[AddressbookModel alloc] init];
            self.addressbookModel.iphoneName = nameStr;
            self.addressbookModel.iphoneNumber = nustring;
            [self.addressbookList addObject:self.addressbookModel];
            
            //去掉电话中的特殊字符
            NSLog(@"姓名=%@, 电话号码是=%@", nameStr, nustring);
        }
    }];
    NSLog(@"个数-- %lu", (unsigned long)self.addressbookList.count);
    [self.tableView reloadData];
}

//提示没有通讯录权限
- (void)showAlertViewAboutNotAuthorAccessContact {
    UIAlertController *alertController = [UIAlertController
                                          alertControllerWithTitle:@"请授权通讯录权限"
                                          message:@"请在iPhone的\"设置-隐私-通讯录\"选项中,允许花解解访问你的通讯录"
                                          preferredStyle: UIAlertControllerStyleAlert];
    
    UIAlertAction *OKAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:nil];
    [alertController addAction:OKAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (NSMutableArray *)addressbookList {
    if (!_addressbookList) {
        _addressbookList = [NSMutableArray arrayWithCapacity:10];
    }
    return _addressbookList;
}

//- (AddressbookModel *)addressbookModel {
//    if (!_addressbookModel) {
//        _addressbookModel = [[AddressbookModel alloc] init];
//    }
//    return _addressbookModel;
//}

@end
